package system.task.quartz;

import lombok.SneakyThrows;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import system.task.TaskExecutor;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * HTTP post job
 */
public class HttpPostJob extends HttpJob implements TaskExecutor {

    public HttpPostJob(String url) {
        super(url);
    }

    @SneakyThrows
    @Override
    protected HttpUriRequest createRequest(URIBuilder builder, HttpJobParam jobParam, HttpClient httpClient) {
        HttpPost post = new HttpPost(builder.build());
        // 设置请求参数
        List<NameValuePair> params = new ArrayList<>();
        for (BasicNameValuePair pair : jobParam.param) {
            params.add(new BasicNameValuePair(pair.getName(), pair.getValue()));
        }
        // 设置请求参数实体
        post.setEntity(new UrlEncodedFormEntity(params, Charset.forName(jobParam.charset)));
        return post;
    }

}
